import { ecs } from 'db://app-game/libs/ecs/ECS';
import { ECSEntity } from 'db://app-game/libs/ecs/ECSEntity';
import { HomeBase } from '../../../biz/home-base/HomeBase';
import { HomeBaseModelComp } from '../../../biz/home-base/model/HomeBaseModelComp';
import { Monster } from '../../../biz/monster/Monster';
import { BatchGenerateMonster } from '../Level.type';

/**  怪兽工厂组件 */
@ecs.register('LevelModelMonsterFatory')
export class LevelModelMonsterFatoryComp extends ecs.Comp {
  /** 当前时间 */
  cT: number = 0;
  /** 当前生成批次 */
  cIndex: number = 0;
  /** 怪兽生成机制数据 */
  batchGenerateMonster: BatchGenerateMonster = [];
  /** 怪兽池 */
  monsterPool: Monster[] = [];
  /** 生成怪兽池 */
  generateMonsterPool: number[] = [];
  /** 生成间隔(秒) */
  generateInterval: number = 1;
  /** 生成间隔计时器 */
  generateIntervalTimer: number = 0;
  /** 生成大本营 */
  homeBase: HomeBase = null;
  reset(entity: ecs.Entity): void {
    this.cT = 0;
    this.cIndex = 0;
    this.batchGenerateMonster = [];
    this.monsterPool = [];
    this.generateMonsterPool = [];
    this.generateInterval = 1;
    this.homeBase = null;
  }
}

/** 怪兽工厂系统 */
@ecs.register('LevelMonsterFactory')
export class LevelMonsterFactorySystem
  extends ecs.ComblockSystem
  implements ecs.IEntityEnterSystem, ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(LevelModelMonsterFatoryComp);
  }
  update(e: ECSEntity, dt: number): void {
    const lmmfc = e.get(LevelModelMonsterFatoryComp);
    // 1.更新时间
    lmmfc.cT += dt;
    // 2.生成怪兽
    this.generateMonster(lmmfc);

    // 3.校验是否已经无怪兽生成
    if (lmmfc.batchGenerateMonster.length <= lmmfc.cIndex) {
      e.remove(LevelModelMonsterFatoryComp);
      return;
    }

    // 4.校验当前批次是否达到生成怪兽时间
    const generateMonster = lmmfc.batchGenerateMonster[lmmfc.cIndex];
    if (lmmfc.cT < generateMonster.time) {
      return;
    }
    // 5.储存怪兽
    for (let i = 0; generateMonster.monsterIds.length < i; i++) {
      const monsterId = generateMonster.monsterIds[i];
      lmmfc.generateMonsterPool.push(monsterId);
    }
  }

  /** 生成怪兽 */
  generateMonster(lmmfc: LevelModelMonsterFatoryComp) {
    // 1.校验是否达到生成间隔
    if (lmmfc.generateMonsterPool.length <= 0) return;
    // 2.计时
    lmmfc.generateIntervalTimer += this.dt;
    if (lmmfc.generateIntervalTimer < lmmfc.generateInterval) return;
    lmmfc.generateIntervalTimer = 0;
    // 3.生成怪兽
    const monsterId = lmmfc.generateMonsterPool.shift();
    const hbmc = lmmfc.homeBase.get(HomeBaseModelComp);
    const monster = ecs.getEntity<Monster>(Monster);
    monster.MonsterModel.id = monsterId;
    monster.load(hbmc.generateParent, hbmc.generatePoint, hbmc.lineup);
  }

  entityEnter(entity: ECSEntity): void {}
}
